<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目名称" prop="subjectName">
        <el-input
          v-model="queryParams.subjectName"
          placeholder="请输入科目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成绩分数" prop="scoreValue">
        <el-input
          v-model="queryParams.scoreValue"
          placeholder="请输入成绩分数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试时间" prop="examTime">
        <el-date-picker
          clearable
          v-model="queryParams.examTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择考试时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否合格" prop="isQualified">
        <el-select
          v-model="queryParams.isQualified"
          placeholder="请选择是否合格"
          clearable
        >
          <el-option label="合格" value="1" />
          <el-option label="不合格" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['score:score:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['score:score:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['score:score:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['score:score:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="scoreList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="成绩ID" align="center" prop="scoreId" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="科目名称" align="center" prop="subjectName" />
      <el-table-column label="成绩分数" align="center" prop="scoreValue" />
      <el-table-column
        label="考试时间"
        align="center"
        prop="examTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.examTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否合格" align="center" prop="isQualified">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.isQualified === '1'"
            >合格</el-tag
          >
          <el-tag type="danger" v-else>不合格</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['score:score:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['score:score:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleApplyResit(scope.row)"
            v-if="scope.row.isQualified === '0'"
            v-hasPermi="['resitExam:resitExam:add']"
            >补考</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改成绩管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" filterable>
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科目" prop="subjectId">
          <el-select
            v-model="form.subjectId"
            placeholder="请选择科目"
            filterable
          >
            <el-option
              v-for="subject in subjectOptions"
              :key="subject.subjectId"
              :label="subject.subjectName"
              :value="subject.subjectId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩分数" prop="scoreValue">
          <el-input-number
            v-model="form.scoreValue"
            placeholder="请输入成绩分数"
            :min="0"
            :max="100"
            :precision="1"
          />
        </el-form-item>
        <el-form-item label="考试时间" prop="examTime">
          <el-date-picker
            clearable
            v-model="form.examTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择考试时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否合格" prop="isQualified">
          <el-radio-group v-model="form.isQualified">
            <el-radio label="1">合格</el-radio>
            <el-radio label="0">不合格</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listScore,
  getScore,
  delScore,
  addScore,
  updateScore,
} from "@/api/score/score";
import { listUser } from "@/api/system/user";
import { listSubject } from "@/api/system/subject";
import { addResitExam, checkScoreResitExam } from "@/api/resitExam/resitExam";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Score",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成绩管理表格数据
      scoreList: [],
      // 用户下拉选项
      userOptions: [],
      // 科目下拉选项
      subjectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        nickName: null,
        subjectId: null,
        subjectName: null,
        scoreValue: null,
        examTime: null,
        isQualified: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户不能为空", trigger: "change" },
        ],
        subjectId: [
          { required: true, message: "科目不能为空", trigger: "change" },
        ],
        scoreValue: [
          { required: true, message: "成绩分数不能为空", trigger: "blur" },
        ],
        examTime: [
          { required: true, message: "考试时间不能为空", trigger: "blur" },
        ],
        isQualified: [
          { required: true, message: "是否合格不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getUsers();
    this.getSubjects();
  },
  methods: {
    /** 查询成绩管理列表 */
    getList() {
      this.loading = true;
      listScore(this.queryParams).then((response) => {
        this.scoreList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUsers() {
      listUser().then((response) => {
        this.userOptions = response.rows;
      });
    },
    /** 查询科目列表 */
    getSubjects() {
      listSubject().then((response) => {
        this.subjectOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scoreId: null,
        userId: null,
        subjectId: null,
        scoreValue: null,
        examTime: null,
        isQualified: "1",
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.scoreId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加成绩管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const scoreId = row.scoreId || this.ids;
      getScore(scoreId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改成绩管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.scoreId != null) {
            updateScore(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScore(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scoreIds = row.scoreId || this.ids;
      this.$modal
        .confirm('是否确认删除成绩管理编号为"' + scoreIds + '"的数据项？')
        .then(function () {
          return delScore(scoreIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "score/score/export",
        {
          ...this.queryParams,
        },
        `score_${new Date().getTime()}.xlsx`
      );
    },
    /** 申请补考操作 */
    handleApplyResit(row) {
      // 首先检查该成绩是否已经申请过补考
      checkScoreResitExam(row.userId, row.subjectId, row.scoreId).then(
        (response) => {
          if (response.code === 200 && response.data) {
            this.$modal.msgError("该成绩已申请过补考，不能重复申请");
            return;
          }

          this.$modal
            .confirm(
              '确认为"' +
                row.nickName +
                '"申请"' +
                row.subjectName +
                '"科目的补考吗？'
            )
            .then(() => {
              // 准备补考申请数据
              const now = new Date();
              const year = now.getFullYear();
              const month = String(now.getMonth() + 1).padStart(2, "0");
              const day = String(now.getDate()).padStart(2, "0");
              const hours = String(now.getHours()).padStart(2, "0");
              const minutes = String(now.getMinutes()).padStart(2, "0");
              const seconds = String(now.getSeconds()).padStart(2, "0");
              const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

              const resitExam = {
                scoreId: row.scoreId,
                userId: row.userId,
                subjectId: row.subjectId,
                originalScore: row.scoreValue,
                applyTime: formattedDate,
                resitStatus: "0", // 待审核
                status: "0", // 正常状态
                remark: "由成绩管理模块申请补考",
              };

              // 提交补考申请
              addResitExam(resitExam)
                .then((response) => {
                  this.$modal.msgSuccess("补考申请成功");
                })
                .catch(() => {});
            })
            .catch(() => {});
        }
      );
    },
  },
};
</script>
